// 引入接口文件
import { getList,update, deleted,create,updatePublished} from './activityListServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import config from 'config/config';
// seckillProductId  projectId houseTypeName detail  area propertyType(商品类型(1,房源，2,停车位，3：商)  seckillPricepropertyType originalPrice initPrice grads securityMoney earnestMoney squarePrice orientation tags imageUrls
// 项目名称  活动名称  商品类型 商品状态
const queryList = [
  {name: '活动名称', type: 'text', key: 'name', value: ''},
  
  { name: '活动时间', type: 'date', key: 'date', value: [] ,options: { showTime: true, format: 'YYYY-MM-DD HH:mm',width:'500' }},
  {
    name: '活动状态', type: 'select', key: 'published', value: '', notNeedAll: true, list: [//（1，未发布。2，已发布，已撤销）
      {id: '', name: '全部'},
      {id: '1', name: '未发布'},
      {id: '2', name: '已发布'},
      {id: '3', name: '已撤销'},
    ]
  },
]

// 初始默认状态
const defultState = {
  loading: false,
  btnLoading: false,
  queryList,
  currentItem: {},
  modalObj:{
    visible:false,
  },
  productSelf: [],
  activeKey: '1',
  // 表格数据
  tableData: {
    dataSource: [
    ],
    total: 0,
    stop:0,
    start:0
  },
  // 表格分页设置
  pageConfig: {
    pageSize: Number.parseInt(config.smallPageSizeList[0]),
    pageNo: ''
  },
  isReloadFirstPage: false

}

// 声明module
const tmpModule = {
  // namespace: 'productListModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          dispatch({ type: 'updateStore', payloand: {...cloneDeep(defultState), ...query} });//每次进去页面先重置状态
          // 执行业务操作
          dispatch({
            type: 'search',
            payload: {}
          }) // end dispatch
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    //查询操作
    *search({ payload = {} }, { call, put, select }) {
      let {queryList,tableData,pageConfig,isReloadFirstPage} = yield select(state => state[tmpModule.namespace])
      const pageSize = pageConfig.pageSize
      //显示loading状态

      //组装接口入参
      let params = {
        sellType: '1',
      };
      queryList.map(item => {
        if(item.value===''){
          return false
        }
        if (item.key === 'date') {
          params.startTime = item.value[0]||'';
          params.endTime = item.value[1]||'';
        } else {
          params[item.key] = item.value;
        }
      })
      yield put({type: 'updateStore', payload: {loading: true, btnLoading: true, tableData: {total: 0},}})
      const {rows, success, msg, total, pageNo} = yield call(getList, {
        ...params,
        pageNo:payload.pageNo ? payload.pageNo : isReloadFirstPage ? 1 : pageConfig.pageNo ,
        pageSize,
      })
      yield put({type: 'updateStore', payload: {loading: false, btnLoading: false,}})
      console.log('数据',rows,success,msg,total,pageNo);
      if (success) {
        let list=rows||[]
        list.map((item,index)=>{
          item.key = index+1;
          item.seckillActivity =item.seckillActivity||{};
        });
        tableData = {
          dataSource: list,
          total:Number(total)
        }
        yield put({
          type: 'updateStore', payload: {
            pageConfig: {...pageConfig, pageNo},
            tableData,
          }
        })
      }
    },

    *pageChange({ payload }, { put, select }) {
      const { pageNo, pageSize } = payload;
      const { pageConfig } =yield select(state => state[tmpModule.namespace])
      yield put({ type: 'updateStore', payload: { pageConfig: { ...pageConfig, ...payload } } });
      yield put({ type: 'search', payload: { pageNo, pageSize } });
    },
    // 查询条件重置
    *queryReset({ }, { put }) {
      yield put({ type: 'updateStore', payload: { queryList: cloneDeep(queryList) } });
      // yield put({ type: 'search' })
    },
    *deleted({payload},{put,call,select}){
      let {success,data}=yield call(deleted,payload)
      if(success){
        message.success('删除成功')
        yield put({type: 'search', payload: {}})
      }
    },
    //改变查询条件
    *inputChange({ payload }, { call, put, select }) {
      let { queryList } = yield select(state => state[tmpModule.namespace])
      const { key, value } = payload;
      let data = queryList.find(item => item.key === key);
      data.value = value;
      yield put({ type: 'updateStore', payload: { queryList: [...queryList, ...data] } });
    },
    // 删除
    *delect({payload }, { put,select,call}) {
      let { queryList ,currentItem,tableData} = yield select(state => state[tmpModule.namespace])
      let {id,index}=payload
      const {success,msg,data} = yield call(delect, {seckillProductId:payload.id });
      console.log('数据',success,msg,data,payload);
      if(success){
        yield put({ type: 'search', payload: {pageNo:1}});
      }
    },

  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
